package com.example.tsbs.config;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

public class StringUtil {

    /**
     *在字符串前面添加空格
     */
    public String string(String str, int length) {
        String paddedString = " ";
        if(str.length() < length) {
             paddedString = StringUtils.repeat(' ', length) + str;
        }
        return paddedString;
    }

    /**String转byte数组
     */
    public static byte[] getBytes(String input) throws UnsupportedEncodingException {
        int byteLen=0;
        byte[] bytes=new byte[3*input.length()];
        for(int i=0;i<input.length();i++) {
            char now=input.charAt(i);
            byte[] nowCharBytes=null;
            if(isChinese(now)) {
                nowCharBytes=(""+now).getBytes("utf-8");
            }else {
                nowCharBytes=(""+now).getBytes();
            }
            for(int j=0;j<nowCharBytes.length;j++) {
                bytes[byteLen++]=nowCharBytes[j];
            }
        }
        return bytes;
    }
    //判断是否为中文
    private static final boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     *产生随机8位字符串(大+小字符+数字)
     */
    public static String randomStr(){
        StringBuilder str = new StringBuilder();
        //随机数生成函数
        Random random = new Random();
        //随机字符串生成
        for (int i = 0; i < 8; i++) {
            //0、1、2从中产生一个随机数，进行随机生成小写字母、大写字母、数字。
            //int ranNum = random.nextInt(3);

            switch (random.nextInt(3)){
                case 0:
                    //生成小写字母
                    char ranLowLetter = (char) ((random.nextInt(26) + 97));
                    str.append(ranLowLetter);
                    break;
                case 1:
                    //生成大写字母
                    char ranUpLetter = (char) ((random.nextInt(26) + 65));
                    str.append(ranUpLetter);
                    break;
                case 2:
                    //生成数字
                    int ranNumOut = random.nextInt(10);
                    str.append(ranNumOut);
                    break;
            }
        }
        return str.toString();
    }

}
